$(function () { // document ready

		var currentDate = moment(new Date()).format('YYYY-MM-DD');

		renderPostModelSel();

		$('#calendar').fullCalendar({
			customButtons: {
				eventModel: {
					text: '模式切换'
				},
				confirmModel: {
					text: '确认模式',
					click: function () {
						confirmModel(model_id);
					}
				},
				eventModelEdit: {
					text: '编辑模式',
					click: function (event) {
						var iHeight = 510;
						var iWidth = 1300;
						var iTop = (window.screen.height - 30 - iHeight) / 2;       //获得窗口的垂直位置;
						var iLeft = (window.screen.width - 10 - iWidth) / 2;
						window.open('modelEdit.html', '_blank', 'height=510, width=1300, top=' + iTop + ', left=' + iLeft + ', toolbar=no, menubar=no, scrollbars=no, resizable=no, location=no, status=no')
					}
				}
			},
			now: currentDate,
			editable: false,
			aspectRatio: 1.8,
			slotWidth: 50,
			scrollTime: '00:00',
			duration: { hours: 0.5 },
			contentHeight: 454,
			header: {
				left: '',
				center: '',
				right: 'confirmModel,eventModelEdit,eventModel'  //timelineDay
			},
			defaultView: 'timelineDay',
			schedulerLicenseKey: 'GPL-My-Project-Is-Open-Source',  //scheduler 商业项目许可证  (须开源)
			views: {
				timelineThreeDays: {
					type: 'timeline',
					duration: { days: 3 }
				}
			},
			resourceAreaWidth: '30%',
			resourceColumns: [
				{
					// group: true,
					labelText: '岗位',
					field: 'building'
				},
				{
					labelText: '班种',
					field: 'class'
				},
				{
					labelText: '班次',
					field: 'shift_id'
				}

			],
			eventOverlap: false, // will cause the event to take up entire resource height
			resources: [
				{ id: '505301', building: '值班站长', class: '大四班', shift_id: '日班' },
				{ id: '505302', building: '值班站长', class: '大四班', shift_id: '夜班' },
				{ id: '505303', building: '行车值班员', class: '大四班', shift_id: '日班' },
				{ id: '505304', building: '行车值班员', class: '大四班', shift_id: '夜班' },
				{ id: '505305', building: '设备值班员', class: '做一休一', shift_id: '日班' },
				{ id: '505306', building: '补票岗站务员', class: '早中班', shift_id: '早班' },
				{ id: '505307', building: '补票岗站务员', class: '早中班', shift_id: '中班' },
				{ id: '505308', building: '巡视岗站务员(机动)', class: '早中班', shift_id: '早班' },
				{ id: '505309', building: '巡视岗站务员(机动)', class: '早中班', shift_id: '中班' },
				{ id: '505310', building: '上行站台岗', class: '早中班', shift_id: '早班' },
				{ id: '505311', building: '上行站台岗', class: '早中班', shift_id: '中班' },
				{ id: '505312', building: '下行站台岗', class: '大四班', shift_id: '日班' },
				{ id: '505313', building: '下行站台岗', class: '大四班', shift_id: '晚班' },
				{ id: '505314', building: '客服岗站务员', class: '早中班', shift_id: '早班' },
				{ id: '505315', building: '客服岗站务员', class: '早中班', shift_id: '中班' },
				// { id: 'g', building: '上行站台岗', class: '早中班', children: [
				// 	{ id: 'g1', class: '早班' },
				// 	{ id: 'g2', class: '中班' }
				// ]},
			],
			events: function (start, end, timezone, callback) {
				start_date = start._d.toISOString().substr(0, 10);
				if(event_flag){
					eventModelRenderData('','');
					event_flag = false;
				}
					// var placeholder = [];
				callback(placeholder);
			},

			// events: [
			// 	{ id: '1', resourceId: '505301', start: '2019-05-07 23:00:00', end: '2019-05-08 01:00:00', title: 'event 1' },
			// 	{ id: '2', resourceId: '505302', start: '05:00:00', end: '22:00:00', title: 'event 2' },
			// 	{ id: '3', resourceId: '505303', start: '07:00:00', end: '08:00:00', title: 'event 3' },
			// 	{ id: '4', resourceId: '505304', start: '03:00:00', end: '08:00:00', title: 'event 4' },
			// 	{ id: '5', resourceId: '505305', start: '23:00:00', end: '24:00:00', title: 'event 5' },
			// 	{ id: '5', resourceId: '505306', start: '00:00:00', end: '01:00:00', title: 'event 6' },
			// ],

			eventRender: function (event, element) {
				element.attr('role', 'button');
				element.attr('tabindex', 0);
				element.attr('data-toggle', 'popover')
				element.popover({
					container: 'body',  //操作弹出框附加在哪个元素上  选择body 不会导致在边界打开弹出框将元素挤变形
					trigger: 'manual',  //触发方式 manual
					placement: 'bottom', //top, bottom, left or right   弹出框弹出位置
					title: '操作',
					html: 'true',    //允许content 使用html
					content: "<div><button type='button' class='btn btn-default' onclick='editPostData()' data-toggle='modal' data-target='#addModal' data-whatever='@edit'>查看</button></div>",   //可以str 也可以 function()返回html str
				})
			},

			eventClick: function (calEvent, jsEvent, view) {

				var a = $('#calendar').fullCalendar('getEventResource', calEvent);
								console.log(calEvent);

				postData = renderPostData(calEvent);
				postData.start = calEvent.start.format('HH:mm:ss');
				postData.end = calEvent.end.format('HH:mm:ss');

								console.log(postData);
				if (!eventTemp) {
					// $(this).popover("show");
					var element = $(this);
					var txt = element.html();
				}
			},

			eventDrop: function (event, delta, revertFunc, jsEvent, ui, view) {
				postData = renderPostData(event);

				postData.start = moment(event.start._i).add(delta._milliseconds, 'milliseconds').format('YYYY-MM-DD HH:mm:ss');
				postData.end = moment(event.end._i).add(delta._milliseconds, 'milliseconds').format('YYYY-MM-DD HH:mm:ss');

				var rescode = eventDataUpdate(postData);
				if (rescode) {
					revertFunc();
				}
			},

			// 修改 fullcalendar.js reportEventResize()方法的返回对象 delta
			eventResize: function (event, delta, revertFunc, jsEvent, ui, view) {

				postData = renderPostData(event);

				if (delta.dateDelta._milliseconds) {
					postData.start = moment(event.start._i).add(delta.dateDelta._milliseconds, 'milliseconds').format('YYYY-MM-DD HH:mm:ss');
					postData.end = event.end._i;
				} else {
					postData.start = event.start._i;
					postData.end = moment(event.end._i).add(delta.durationDelta._milliseconds, 'milliseconds').format('YYYY-MM-DD HH:mm:ss');
				}

				var rescode = eventDataUpdate(postData);
				if (rescode) {
					revertFunc();
				}
				console.log(postData);
			},
		});



	});

	var eventTemp;  //事件点击
	var eventData;
	var start_date; //当前页面日期
	var placeholder = [];  //fullcalendar 事件源 占位符
	var model_obj = {};  //模式切换下拉框
	var model_name = '';
	var model_id = '';
	var event_flag = true;

	var postData = {
		id: '',
		resourceId: '',
		start: '',    //开始时间
		end: '',      //结束时间
		post: '',     //岗位
		postValue: '',
		area: '',     //区域
		areaValue: '',
		postId: '',   //岗点
		postIdValue: ''
	}

	function alertJss() {
		toastr["warning"]("你有新消息了!");
	}


	//event 弹出操作框点击事件监听
	$("body").on("click", function (event) {
		var target = $(event.target);

		if (!target.hasClass('fc-title')            //如果点击的不是 event 中的dom元素 就关闭操作弹出框
			&& !target.parent().hasClass('fc-event')
			&& !target.hasClass('fc-event')) {
			$('.fc-event').popover('hide');
			eventTemp = null;
		} else {
			var c = target[0].tagName.toLowerCase();  //拿到当前选中的event 去和上次点击的event对比 
			var event;
			if (c == 'span') {
				event = target.parent().parent();
			} else {
				event = target.parent();
			}
			if (eventTemp) {
				if (event.attr('aria-describedby') == eventTemp.attr('aria-describedby')) {
					$(eventTemp).popover('hide');    //和上次点击的相同 则关闭此event
					eventTemp = null;
				} else {
					$(eventTemp).popover('hide');   //不同也关闭此event 再打开当前点击的event
					$(event).popover('show');
					eventTemp = event;
				}
			} else {
				$(event).popover('show');             //不存在上次点击的event 则直接打开此event弹出操作框
				eventTemp = event;
			}
		}
	});

	//弹出框
	toastr.options = {
		closeButton: true,
		debug: false,
		progressBar: true,
		positionClass: "toast-top-center",
		onclick: null,
		showDuration: "300",
		hideDuration: "1000",
		timeOut: "2000",
		extendedTimeOut: "1000",
		showEasing: "swing",
		hideEasing: "linear",
		showMethod: "fadeIn",
		hideMethod: "fadeOut"
	};

	$('.postBtn').on('click', function () {
		$('#addModal').modal('hide');
	});



	$('body').on("click", '.eventModelMenu a', function (event) {
		var target = $(event.target);
		model_name = target.text();
		model_id = target.attr('model_id');
		eventModelRenderData(start_date, model_id);
		$('#model_name_input').val(model_name);
	})

	//清空表单数据
	$('.modal').on('hidden.bs.modal', function () {
		$('#start_time').val('');
		$('#end_time').val('');
		$('#postIdSelectInputText').val('');
		$('#areaSelectInputText').val('');
		$('#postSelectInputText').val('');
		$('#workItemSelectInputText').val('');
		postData = {};
	});


	$('.modal').on('show.bs.modal', function (event) {
		var recipient = $(event.relatedTarget).data('whatever');
		var modal = $(this)
		if (recipient) {
			modal.find('.modal-title').text('查看布岗');
			$('#start_time').val(postData.start);
			$('#end_time').val(postData.end);
			$('#postIdSelectInputText').val(postData.postId);
			$('#areaSelectInputText').val(postData.area);
			$('#postSelectInputText').val(postData.post);
			$('#workItemSelectInputText').val(postData.item);

			$('.postBtn').attr('id', 'post-edit');
		} else {
			modal.find('.modal-title').text('新增布岗');
			$('.postBtn').attr('id', 'post-submit');
		}

	})

	function editPostData() {
		// $('.modal').modal('show')
	}

	function renderPostData(event) {
		postData = {
			id: event.id,
			resourceId: event.resourceId,
			// start: calEvent.start._i,    //开始时间
			// end: calEvent.end._i,      //结束时间
			post: event.post,     //岗位
			postValue: event.postValue,
			area: event.area,     //区域
			areaValue: event.areaValue,
			postId: event.postId,   //岗点
			postIdValue: event.postIdValue,
			item: event.item
		}
		return postData;
	}

	function eventModelRenderData(start_date, model_namearg) {
		$.ajax({
			url: '/post/modelPostEvent	',
			type: 'GET',
			data: {
				//				date: start_date,
				modelName: model_namearg
			},
			success: function (data) {
				if (data.code == 'success') {
					var source = [];
					if (data.data && data.data.length != 0) {
						model_id = data.data[0].modelName;
						model_name = model_obj[model_id];
						$('#model_name_input').val(model_name);
						data.data.forEach(function (element) {
							source.push({
								title: element.title,
								id: element.id,
								resourceId: element.resourceId,
								start: element.start,
								end: element.end,
								post: element.post,
								postValue: element.postValue,
								postId: element.postId,
								postIdValue: element.postIdValue,
								area: element.area,
								areaValue: element.areaValue,
								item: element.item
							})
						});
					}
					// $('#calendar').fullCalendar('addEventSource',events);
					// $('#calendar').fullCalendar('events',events);
					placeholder = source;
					$('#calendar').fullCalendar('refetchEvents');
					// callback(events);
				} else {
					toastr[data.code](data.message);
				}
			}
		});
	}

	function renderPostModelSel() {
		$.ajax({
			url: '/post/modelName',
			type: 'GET',
			data: {},
			success: function (data) {
				if (data.code == 'success') {
					model_obj = data.data;
					var modelliHtml = '';
					var modalDropDown = "<ul class='dropdown-menu eventModelMenu' aria-labelledby='eventModel'>"
					if (!model_obj) {
						modelliHtml += "<li><a href='#'>当前无模板</a></li>"
					} else {
						for(var obj in model_obj){
							modelliHtml += "<li><a href='#' model_id='"+ obj +"'>" + model_obj[obj] + "</a></li><li role='separator' class='divider'></li>";
						}
					}
					modalDropDown += modelliHtml + '</ul>';
					$('.fc-eventModel-button').attr({ 'data-toggle': 'dropdown', 'id': 'eventModel', 'aria-haspopup': 'true', 'aria-expanded': 'true' });
					$('.fc-eventModel-button').addClass('dropdown-toggle');

					$('.fc-right .fc-button-group').prepend('<div class="dropdown eventMOdelDropDown"></div>');
					$('.eventMOdelDropDown').append($('.fc-eventModel-button'));
					$(modalDropDown).insertAfter($('.fc-eventModel-button'));
				} else {
					toastr[data.code](data.message);
				}
			}
		});
	}

	function confirmModel(model_id) {
		$.ajax({
			url: '/post/confirmModel',
			type: 'GET',
			data: { modelId: model_id },
			success: function (data) {
				if (data.code == 'success') {
					toastr[data.code](model_name + ' 模板数据已发送！');
				} else {
					toastr[data.code](data.message);
				}
			}
		});
	}